package com.hare.auth.exception;

import com.alibaba.fastjson.JSONObject;

import com.hare.common.global.constant.BaseConstant;
import com.hare.common.global.enums.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: Hare
 * @description: 授权失败处理类
 * @author: Hare
 * @create: 2022-11-16 13:24
 * @Version 6.0.1
 **/
@Component
public class FailAccessDeniedHandler implements AccessDeniedHandler {


    /**
     * 授权失败处理
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String message = String.format("无此权限");
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        result.put("success", BaseConstant.ERROR_BON);
        result.put("code", ResultCode.FORBIDDEN.getCode());
        result.put("message", message);
        result.put("data", "token无效或过期,请重新登录");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
